package com.lzt.app

import java.text.SimpleDateFormat
import java.util.{Calendar, Date}

object StringUtil {
  private val MINTUE_FORMAT = "yyyyMMddHHmm"
  private val DETAIL_FORMAT = "yyyyMMddHHmmss"
  private val DAY_FORMAT = "yyyyMMdd"

  /**
    *
    * @param t
    * @return yyyyMMddHHmm
    */
  def dateFormat(t: Date, format: String = MINTUE_FORMAT): String = {
    new SimpleDateFormat(format).format(t)
  }

  /**
    *
    * @param str yyyy-MM-dd HH:mm:ss
    * @return
    */
  def parseDate(str: String): Date = {
    str match {
      case str if str.length == DAY_FORMAT.length =>
        new SimpleDateFormat(DAY_FORMAT).parse(str)
      case str if str.length == DETAIL_FORMAT.length =>
        new SimpleDateFormat(DETAIL_FORMAT).parse(str)
      case _ => null
    }
  }

  def isNull(s: String): Boolean = {
    s == null || "".equals(s.trim)
  }

  def notNull(s: String): Boolean = {
    !isNull(s)
  }

  /**
    * 为日期增加分钟数
    *
    * @param date   日期
    * @param minute 分钟，可以为负
    * @return
    */
  def addMinute(date: Date, minute: Int): Date = {
    val calendar = Calendar.getInstance
    calendar.setTime(date)
    calendar.add(Calendar.MINUTE, minute)
    calendar.getTime
  }

  /**
    * 设置秒
    *
    * @param date   时间
    * @param second 秒
    * @return
    */
  def setSecond(date: Date, second: Int): Date = {
    val calendar = Calendar.getInstance
    calendar.setTime(date)
    calendar.set(Calendar.SECOND, second)
    calendar.getTime
  }

  /**
    * 返回前一分钟
    *
    * @param date
    * @return
    */
  def getLastMinute(date: Date = new Date()): (String, String) = {
    val now = setSecond(date, 0)
    val start = dateFormat(addMinute(now, -1))
    val end = dateFormat(now)
    (start, end)
  }

  /**
    * 返回当天8点与晚8点
    *
    * @param date
    * @return
    */
  def getTodayMinute(date: Date = new Date()): (String, String) = {
    val today = dateFormat(date, DAY_FORMAT)
    val start = s"${today}0800"
    val end = s"${today}2000"
    (start, end)
  }
}
